package com.ten.mall.utils;

import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.TreeMap;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.ten.mall.vo.weixin.Button;
import com.ten.mall.vo.weixin.ClickButton;
import com.ten.mall.vo.weixin.Menu;
import com.ten.mall.vo.weixin.TemplateData;
import com.ten.mall.vo.weixin.ViewButton;
import com.ten.mall.vo.weixin.WechatTemplateMsg;

public class WeiXinUtils {
	private static Logger log = LoggerFactory.getLogger(WeiXinUtils.class);
	/**
	 * 创建患者按钮
	 * @param shopUrl
	 * @param orderUrl
	 * @return
	 */
	public static String initViewUserMenu(String shopUrl,String orderUrl){
		ViewButton button2 = new ViewButton();
		ClickButton button1=new ClickButton();
		ViewButton button3 = new ViewButton();
		button2.setName("购买药品");
		button2.setType("view");
		button2.setUrl(shopUrl);
		button1.setName("相关知识");
		button1.setType("click");
		button1.setKey("12345");
		button3.setName("个人中心");
		button3.setType("view");
		button3.setUrl(orderUrl);
		Menu menu =new Menu();
		Button [] btn ={button1,button2,button3};
		menu.setButton(btn);
		String result =JSON.toJSONString(menu);
		return result;
	}
	/**
	 * 创建医生按钮
	 * @param shopUrl
	 * @param orderUrl
	 * @return
	 */
	public static String initViewDoctorMenu(String shopUrl,String orderUrl){
		ViewButton button2 = new ViewButton();
		ClickButton button1=new ClickButton();
		ViewButton button3 = new ViewButton();
		button2.setName("购买药品");
		button2.setType("view");
		button2.setUrl(shopUrl);
		button1.setName("相关知识");
		button1.setType("click");
		button1.setKey("12345");
		button3.setName("个人中心");
		button3.setType("view");
		button3.setUrl(orderUrl);
		Menu menu =new Menu();
		Button [] btn ={button1,button2,button3};
		menu.setButton(btn);
		String result =JSON.toJSONString(menu);
		return result;
	}
	/**
	 * 创建销售员按钮
	 * @param shopUrl
	 * @param orderUrl
	 * @return
	 */
	public static String initViewSalemanMenu(String shopUrl,String orderUrl){
		ViewButton button2 = new ViewButton();
		ClickButton button1=new ClickButton();
		ViewButton button3 = new ViewButton();
		button2.setName("购买药品");
		button2.setType("view");
		button2.setUrl(shopUrl);
		button1.setName("相关知识");
		button1.setType("click");
		button1.setKey("12345");
		button3.setName("个人中心");
		button3.setType("view");
		button3.setUrl(orderUrl);
		Menu menu =new Menu();
		Button [] btn ={button1,button2,button3};
		menu.setButton(btn);
		String result =JSON.toJSONString(menu);
		return result;
	}
	/**
	 * 创建店员按钮
	 * @param shopUrl
	 * @param orderUrl
	 * @return
	 */
	public static String initViewDianyuanMenu(String shopUrl,String orderUrl){
		ClickButton button1=new ClickButton();
		ViewButton button3 = new ViewButton();
		button1.setName("相关知识");
		button1.setType("click");
		button1.setKey("12345");
		button3.setName("个人中心");
		button3.setType("view");
		button3.setUrl(orderUrl);
		Menu menu =new Menu();
		Button [] btn ={button1,button3};
		menu.setButton(btn);
		String result =JSON.toJSONString(menu);
		return result;
	}
	/**
	 * 创建医生按钮
	 * @param shopUrl
	 * @param orderUrl
	 * @return
	 */
	public static ViewButton initViewMenu(String shopUrl,String name){
		ViewButton button2 = new ViewButton();
		
		button2.setName("购买药品");
		button2.setType("view");
		button2.setUrl(shopUrl);
		
		return button2;
	}
	/**
	 * 创建菜单
	 * @return
	 * @throws Exception 
	 */
	public static String createMenu(String token,String menu) throws Exception{
		String url ="https://api.weixin.qq.com/cgi-bin/menu/create?access_token="+token;
		String result =doPostStr(url,menu);
		return result;
	}
	
	/**
	 * POST请求
	 * @param url
	 * @param outStr
	 * @return
	 * @throws ParseException
	 * @throws IOException
	 */
	public static String doPostStr(String url,String outStr) throws Exception{
		DefaultHttpClient client = new DefaultHttpClient();
		HttpPost httpost = new HttpPost(url);
		String result = null;
		httpost.setEntity(new StringEntity(outStr,"UTF-8"));
		HttpResponse response = client.execute(httpost);
		result = EntityUtils.toString(response.getEntity(),"UTF-8");
		return result;
	}
	
	/** 
	 * 创建永久二维码(字符串) 
	 *  
	 * @param accessToken 
	 * @param sceneStr 场景str 
	 * @return 
	 */  
	public static String createForeverStrTicket(String accessToken, String sceneStr) {  
	    String url ="https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token="+accessToken;
	    Map<String, String> intMap = new HashMap<String, String>();  
	    intMap.put("scene_str", sceneStr);  
	    Map<String, Map<String, String>> mapMap = new HashMap<String, Map<String, String>>();  
	    mapMap.put("scene", intMap);  
	    Map<String, Object> paramsMap = new HashMap<String, Object>();  
	    paramsMap.put("action_name","QR_LIMIT_STR_SCENE");  
	    paramsMap.put("action_info", mapMap);  
	    String data =JSON.toJSONString(paramsMap);
	    String response= HttpClientUtil.doPostJson(url, data);  
	    return response;
	}  
	/**
	 * 获取用户信息
	 * @param accessToken
	 * @param openId
	 * @param lang
	 * @return
	 */
	public static String getUserInfo(String accessToken,String openId,String lang){
		String urlUser = "https://api.weixin.qq.com/cgi-bin/user/info";
		Map<String,String> param =new HashMap<>();
		param.put("access_token", accessToken);
		param.put("openid",openId);
		param.put("lang", lang);
		String ss =HttpClientUtil.doGet(urlUser, param);
		if(ss.indexOf("errcode")<0){
			return ss;
		}
		return "error";
	}
	/**
	 * 获取用户的access_token 网页版
	 * @param appid
	 * @param secret
	 * @param code
	 * @return
	 */
	public static String getWebAuthorToken(String appid,String secret,String code){
		String url="https://api.weixin.qq.com/sns/oauth2/access_token?appid="+appid+"&secret="+secret+"&code="+code+"&grant_type=authorization_code";
		String rs =HttpClientUtil.doGet(url);
		return rs;
	}
	/**
	 * 获取用户的网页用户名
	 * @param access_token
	 * @param openid
	 * @return
	 */
	public static String getWebUserInfo(String access_token,String openid){
		String url ="https://api.weixin.qq.com/sns/userinfo?access_token="+access_token+"&openid="+openid+"&lang=zh_CN";
		String rs =HttpClientUtil.doGet(url);
		return rs;
	}
	/**
	 * 创建回调地址
	 * @param appId
	 * @param dir
	 * @return
	 */
	public static String createMyEncodeUrl(String appId,String dir){
		String url ="https://open.weixin.qq.com/connect/oauth2/authorize?";
		  //String dir ="http://myweixin.s3.natapp.cc/phone/test";
		  String ss =URLEncoder.encode(dir);
		  StringBuffer sb =new StringBuffer(url);
		  sb.append("appid=").append(appId)
		  .append("&redirect_uri=").append(ss).append("&response_type=")
		  .append("code").append("&scope=").append("snsapi_userinfo")
		  .append("&state=123").append("#wechat_redirect");
		  log.info("url:"+sb.toString());
		return sb.toString();
	}
	/**
	 * 产生随机字符串
	 * @param length
	 * @return
	 */
	public static String CreateNoncestr(int length) { 
		String chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; 
		String res = ""; 
		for (int i = 0; i < length; i++) { 
		Random rd = new Random(); 
		res += chars.indexOf(rd.nextInt(chars.length() - 1)); 
		} 
		return res; 
		} 
	
	/**
     * 解析微信服务器发来的请求
     * @param inputStream
     * @return 微信返回的参数集合
	 * @throws Exception 
     */
    public static Map<String,Object> parseXml(InputStream inputStream) throws Exception {
        Map<String,Object> map = new HashMap<>();
        try {
            //获取request输入流
            SAXReader reader = new SAXReader();
            Document document = reader.read(inputStream);
            //得到xml根元素
            Element root = document.getRootElement();
            //得到根元素所有节点
            List<Element> elementList = root.elements();
            //遍历所有子节点
            for (Element element:elementList){
                map.put(element.getName(),element.getText());
            }
            //释放资源
            inputStream.close();
        } catch (Exception e) {
            throw new Exception("微信工具类:解析xml异常",e);
        }
        return map;
    }
    
    public static String sendTempleteMsg(String access_token,String openId,String templateId,Map<String,TemplateData> map) throws Exception{
    	String url ="https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="+access_token;
    	TreeMap<String,TreeMap<String,String>> params = new TreeMap<String,TreeMap<String,String>>(); 
    	params.put("first",WechatTemplateMsg.item(map.get("first").getValue(), map.get("first").getColor()));
    	params.put("keyword1",WechatTemplateMsg.item(map.get("keyword1").getValue(), map.get("keyword1").getColor()));
    	params.put("keyword2",WechatTemplateMsg.item(map.get("keyword2").getValue(), map.get("keyword2").getColor()));  
        params.put("keyword3",WechatTemplateMsg.item(map.get("keyword3").getValue(), map.get("keyword3").getColor()));  
        params.put("keyword4",WechatTemplateMsg.item(map.get("keyword4").getValue(), map.get("keyword4").getColor()));  
        params.put("remark",WechatTemplateMsg.item(map.get("remark").getValue(), map.get("remark").getColor()));
        WechatTemplateMsg wechatTemplateMsg = new WechatTemplateMsg();  
        wechatTemplateMsg.setTemplate_id(templateId);    
        wechatTemplateMsg.setTouser(openId);  
        //wechatTemplateMsg.setUrl("http://www.baidu.com");  
        wechatTemplateMsg.setData(params);  
        String data =JSON.toJSONString(wechatTemplateMsg);
        String ss =doPostStr(url, data);
    	return ss;
    }
    /*public static void main(String[] args) {
    	try {
			String yy =sendTempleteMsg("7_P9mwP82eiBoe6YIUe7XNnInTImFQl9K3Rk2SRIl6Dil1eHk8W3zjq_RzCC90B1XYlrJsAR4kvaxdqF5PkHcN7hjMGENW25P1U_xasBZPW-VhO6S1-82d4x01j_G9PskTkMPT3vmI0dShJ5N6FUIbAGAODR",
					"okz6Vt62VuNW_JHmlMWmniL8OLGg","zlnZUIHMkCY78DKrt_Ag5CAZbuHWrLAtY04X8w65X8s");
			System.out.println("yy:"+yy);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}*/
}
